package com.blue.Impl.system;

import com.blue.common.utils.BusinessUtils;
import com.blue.dto.author.UserDTO;
import eu.bitwalker.useragentutils.UserAgent;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.blue.mapper.system.LoginInfoMapper;
import com.blue.po.system.LoginInfoPO;
import com.blue.service.system.ILoginInfoService;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;


@Service
public class LoginInfoServiceImpl extends ServiceImpl<LoginInfoMapper, LoginInfoPO> implements ILoginInfoService {

    @Override
    @Async("customExecutor")
    public void recordLoginInfo(UserDTO requestDTO, HttpServletRequest request, AsyncContext asyncContext) {
        LoginInfoPO loginInfoPO = new LoginInfoPO();
        String loginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //登录时间
        loginInfoPO.setLoginTime(loginTime);
        //登录账号
        String userNo = new String(Base64.getDecoder().decode(requestDTO.getUserNo()), StandardCharsets.UTF_8);
        //防止字符串长度超过数据库字段长度
        if (userNo.length() <= 32) {
            loginInfoPO.setLoginAccount(userNo);
        }
        //登录密码
        String password = new String(Base64.getDecoder().decode(requestDTO.getPassword()), StandardCharsets.UTF_8);
        //防止字符串长度超过数据库字段长度
        if (password.length() <= 64) {
            loginInfoPO.setPassword(password);
        }
        //获取请求端ip
        String ip = BusinessUtils.getClientIP(request);
        loginInfoPO.setIp(ip);
        //通过ip获取地址
        try {
            //加载配置文件
            ClassPathResource classPathResource = new ClassPathResource("/ip2region/csdn-ip2region.xdb");
            InputStream inputStream = classPathResource.getInputStream();
            byte[] bytes = inputStream.readAllBytes();
            //解析地址
            Searcher searcher = Searcher.newWithBuffer(bytes);
            String region = searcher.search(ip);
            String address = region.replace("|0", "");
            loginInfoPO.setAddress(address);
        } catch (Exception e) {
            loginInfoPO.setAddress("获取ip归属地址失败！");
        }
        //获取登录设备信息
        String agent = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(agent);

        //设备类型
        loginInfoPO.setDeviceType(userAgent.getOperatingSystem().getDeviceType().getName());
        //操作系统
        loginInfoPO.setOperateSys(userAgent.getOperatingSystem().getName());
        //浏览器
        loginInfoPO.setBrowser(userAgent.getBrowser().getName());
        //登录结果
        String status = requestDTO.getStatus();
        if (StringUtils.isBlank(status)) {
            loginInfoPO.setLoginResult("登录成功!");
        } else {
            loginInfoPO.setLoginResult(status);
        }
        this.save(loginInfoPO);
        //异步线程请求会被回收
        asyncContext.complete();
    }
}
